<template>
  <div style="background-color: white !important">
    <el-row align="middle">
      <el-col :span="1" />
      <el-col :span="23">
        <el-row style="width: 100%">
          <el-col :span="22">
            <!-- <el-row class="mt-15" justify="center">
              <span class="h1-font">采购部月生产报告</span>
            </el-row> -->
            <el-row class="mt-15">
              <span class="h2-font">
                报告期：<el-date-picker
                  style="width: 140px"
                  v-model="reportMonth"
                  @change="reportMonthChange"
                  type="month"
                  format="YYYY年M月" />
              </span>
            </el-row>
            <el-row class="mt-15"><span class="h2-font">一、部室项目执行情况</span></el-row>
            <el-row class="mt-15">
              <span class="h3-font">1、项目详细</span>
              <el-text size="small" type="primary" tag="b" style="font-weight: bold">（项目打勾则表示导出月报）</el-text>
            </el-row>
            <el-row class="mt-15">
              <el-table
                header-cell-class-name="header-cell"
                :data="projectDetailsData"
                v-loading="isLoading"
                element-loading-text="加载中 . . ."
                element-loading-background="rgba(0, 0, 0, 0.8)"
                size="small"
                border>
                <el-table-column label="是否导出" width="80" align="center">
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.projectExport" />
                  </template>
                </el-table-column>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectStage" label="项目阶段" header-align="center" width="150">
                  <template #default="scope">
                    <el-select
                      style="width: 100%"
                      v-model="scope.row.projectStage"
                      filterable
                      allow-create
                      :reserve-keyword="false"
                      placeholder="请选择或填写">
                      <el-option label="总承包" value="总承包" />
                      <el-option label="管理包" value="管理包" />
                      <el-option label="投标报价" value="投标报价" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="采购经理" header-align="center" width="250">
                  <template #default="scope">
                    <el-select
                      style="width: 100%"
                      v-model="scope.row.purchasingManagerList"
                      multiple
                      :multiple-limit="3"
                      collapse-tags
                      collapse-tags-tooltip
                      :max-collapse-tags="1"
                      filterable
                      default-first-option
                      :reserve-keyword="false"
                      placeholder="请选择/最多选择三人"
                      clearable>
                      <el-option v-for="item in purchasingEmpData" :label="item.empCname" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
              <!-- <el-table header-cell-class-name="header-cell" :data="projectDetailsData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center" >
                  <template #default="scope">
                    <span >[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectStage" label="项目阶段" header-align="center" width="150" />
                <el-table-column prop="purchasingManager" label="采购经理" header-align="center" width="250">
                  <template #default="scope">
                    <span>{{ scope.row.purchasingManager && scope.row.purchasingManager.replaceAll(",", "，") }}</span>
                  </template>
                </el-table-column>
              </el-table> -->
            </el-row>
            <el-row class="mt-15"><span class="h3-font">2、部室项目执行情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectSituationData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectSituation" label="执行情况" header-align="center" width="300" />
                <el-table-column prop="projectProblem" label="存在问题" header-align="center" width="200" />
                <el-table-column prop="projectSolution" label="解决措施" header-align="center" width="200" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h3-font">3、部室项目工作量完成情况</span></el-row>
            <el-row class="mt-15">
              <span class="h3-font">1）询价报价情况</span><span class="h3-font-nobold">（包括总包项目和管理包项目）</span>
            </el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectInquiryQuotationData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectInquiry" label="发出询价（份）" align="center" width="120" />
                <el-table-column prop="projectQuotation" label="收到报价（份）" align="center" width="120" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h3-font">2）合同签订情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectContractData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectContractCount" label="合同份数" align="center" width="120" />
                <el-table-column prop="projectContractAmount" label="合同金额（万元）" header-align="center" align="right" width="140" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h3-font">3）厂商返回设计文件的接收和提交情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectDesignDocData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="docReturnCount" label="计划返回（份）" align="center" width="110" />
                <el-table-column prop="docReceiveCount" label="实际接收（份）" align="center" width="110" />
                <el-table-column prop="docSubmitCount" label="提交设计（份）" align="center" width="110" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h3-font">4）催交和中间检验情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectDeliveryInspectionData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectOnlineDeliveryCount" label="联系催交（次）" align="center" width="110" />
                <el-table-column prop="projectOfflineDeliveryCount" label="到场催交（次）" align="center" width="110" />
                <el-table-column prop="projectSupervisionCount" label="驻场监造（次）" align="center" width="110" />
                <el-table-column prop="projectInspectionCount" label="中间检验（次）" align="center" width="110" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h3-font">5）现场接保检工作情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectReceiveInspectionData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectReceiveGoodsCount" label="接货（批）" align="center" width="80" />
                <el-table-column prop="projectOpenboxCount" label="开箱检验" align="center" width="80" />
                <el-table-column prop="projectSupervisionInspectionCount" label="监理报检" align="center" width="80" />
                <el-table-column prop="projectInstorageCount" label="入库" align="center" width="80" />
                <el-table-column prop="projectOutstorageCount" label="出库" align="center" width="80" />
                <el-table-column prop="projectBackupHandoverCount" label="备件移交" align="center" width="80" />
                <el-table-column prop="projectDocArrangementCount" label="文件整理" align="center" width="80" />
                <el-table-column prop="projectFactoryServiceCount" label="厂商服务" align="center" width="80" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h3-font">6）货款支付和发票收取情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectPaymentInvoiceData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectPaymentCount" label="支付申请（次）" align="center" width="110" />
                <el-table-column prop="projectApplyPassCount" label="申请批准（次）" align="center" width="110" />
                <el-table-column prop="projectActualPayCount" label="实际付出（次）" align="center" width="110" />
                <el-table-column prop="projectInvoiceCount" label="收到发票（份）" align="center" width="110" />
                <el-table-column prop="projectTransferFinanceCount" label="移交财务（份）" align="center" width="110" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h2-font">二、部室项目控制点执行情况</span></el-row>
            <el-row class="mt-15"><span class="h3-font">1、控制点完成情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectControlPointData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="本月" align="center">
                  <el-table-column prop="projectLastMonthLegacyCount" label="月前遗留" align="center" width="65" />
                  <el-table-column prop="projectTheMonthPlanCount" label="本月计划" align="center" width="65" />
                  <el-table-column prop="projectAllPlanCount" label="合计计划" align="center" width="65" />
                  <el-table-column prop="projectCompleteCount" label="完成" align="center" width="65" />
                  <el-table-column prop="projectUncompleteCount" label="未完" align="center" width="65" />
                  <el-table-column prop="projectCompleteRate" label="完成率" align="center" width="60">
                    <template #default="scope">
                      <span>
                        {{ scope.row.projectCompleteRate !== null ? Number(scope.row.projectCompleteRate * 100).toFixed(0) + "%" : null }}
                      </span>
                    </template>
                  </el-table-column>
                </el-table-column>
                <el-table-column label="未完成原因" align="center">
                  <el-table-column prop="projectOwnerReasonCount" label="业主原因" align="center" width="65" />
                  <el-table-column prop="projectUpstreamReasonCount" label="上游原因" align="center" width="65" />
                  <el-table-column prop="projectProfessionalReasonCount" label="专业原因" align="center" width="65" />
                </el-table-column>
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h3-font">2、未完控制点原因说明</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectUncompleteReasonData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectMainControlContent" label="主要控制点内容" header-align="center" width="150" />
                <el-table-column prop="projectUncompleteReason" label="未完原因" header-align="center" width="150" />
                <el-table-column prop="projectSolution" label="解决措施" header-align="center" width="150" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h2-font">三、部室人力资源管理</span></el-row>
            <el-row class="mt-15"><span class="h3-font">1、部室人力资源状态</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="employeeResourcesData" size="small" border show-summary>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="employeeType" align="center" widtn="150" />
                <el-table-column prop="regularNum" label="正式员工数量" align="center">
                  <template #default="scope">
                    <el-input-number
                      style="width: 100%"
                      v-model="scope.row.regularNum"
                      @input="
                        (val) => {
                          employeeNumInput(val, 'employee', scope.row);
                        }
                      "
                      :min="0"
                      :controls="false" />
                  </template>
                </el-table-column>
                <el-table-column prop="rehireNum" label="返聘员工数量" align="center">
                  <template #default="scope">
                    <el-input-number
                      style="width: 100%"
                      v-model="scope.row.rehireNum"
                      @input="
                        (val) => {
                          employeeNumInput(val, 'rehire', scope.row);
                        }
                      "
                      :min="0"
                      :controls="false" />
                  </template>
                </el-table-column>
                <el-table-column label="外聘员工" align="center">
                  <el-table-column prop="externalNum" label="外聘员工数量" align="center">
                    <template #default="scope">
                      <el-input-number
                        style="width: 100%"
                        v-model="scope.row.externalNum"
                        @input="
                          (val) => {
                            employeeNumInput(val, 'external', scope.row);
                          }
                        "
                        :min="0"
                        :controls="false" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="borrowNum" label="借用员工数量" align="center">
                    <template #default="scope">
                      <el-input-number
                        style="width: 100%"
                        v-model="scope.row.borrowNum"
                        @input="
                          (val) => {
                            employeeNumInput(val, 'borrow', scope.row);
                          }
                        "
                        :min="0"
                        :controls="false" />
                    </template>
                  </el-table-column>
                </el-table-column>
                <el-table-column prop="allNum" label="合计" align="center" />
              </el-table>
            </el-row>
            <el-row v-if="false" class="mt-15"><span class="h3-font">4、部室人力负荷情况</span></el-row>
            <el-row v-if="false" class="mt-15">
              <el-row style="width: 100%">
                <el-col :span="12"><div ref="lastMonthLoadChartRef" style="width: 100%; height: 400px"></div></el-col>
                <el-col :span="12"><div ref="theMonthLoadChartRef" style="width: 100%; height: 400px"></div></el-col>
              </el-row>
            </el-row>
            <el-row class="mt-15"><span class="h2-font">四、技术及业务培训情况</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="trainingData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="trainingDate" label="时间" align="center" width="140" />
                <el-table-column prop="trainingAdress" label="地点" header-align="center" width="200" />
                <el-table-column prop="trainingTheme" label="培训内容" header-align="center" />
                <el-table-column prop="trainingSpeecher" label="主讲人" header-align="center" width="120" />
                <el-table-column prop="trainingPartCount" label="参加人数" align="center" width="80" />
              </el-table>
            </el-row>
            <el-row class="mt-15"><span class="h2-font">五、下期的主要工作安排</span></el-row>
            <el-row class="mt-15"><span class="h3-font">1、项目运行过程中的主要工作</span></el-row>
            <el-row class="mt-15">
              <el-table header-cell-class-name="header-cell" :data="projectFocusData" size="small" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="projectName" label="项目名称" header-align="center">
                  <template #default="scope">
                    <span>[{{ scope.row.projectCode }}]</span>
                    <span>{{ scope.row.projectName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectFocusContent" label="重点关注的内容" header-align="center" />
              </el-table>
            </el-row>
          </el-col>
          <el-col :span="2">
            <el-row style="height: 100%"></el-row>
            <el-affix class="ml-15" position="bottom" :offset="40">
              <el-button @click="exportHandle" type="primary" size="large">导出报告</el-button>
            </el-affix>
          </el-col>
        </el-row>
      </el-col>
      <!-- <el-col :span="1" /> -->
    </el-row>
  </div>
</template>
<script setup>
import JSZipUtils from "jszip-utils";
import JSZip from "pizzip";
import { saveAs } from "file-saver";
import { ref, onMounted } from "vue";
import { ElMessage, dayjs } from "element-plus";
import "dayjs/locale/zh-cn";
import * as echarts from "echarts";
import ReportService from "@/https/api/report";
import Decimal from "decimal.js";

// 报告期
const reportMonth = ref(dayjs(new Date()).format("YYYY-MM"));
// 项目详细情况
const projectDetailsData = ref([]);
// 项目执行情况
const projectSituationData = ref([]);
// 项目询价报价情况
const projectInquiryQuotationData = ref([]);
// 项目合同签订情况
const projectContractData = ref([]);
// 厂商返回设计文件接收和提交情况
const projectDesignDocData = ref([]);
// 催交和中间检验情况
const projectDeliveryInspectionData = ref([]);
// 现场接保检工作情况
const projectReceiveInspectionData = ref([]);
// 货款支付和发票收取情况
const projectPaymentInvoiceData = ref([]);
// 项目控制点完成情况
const projectControlPointData = ref([]);
// 未完控制点原因说明
const projectUncompleteReasonData = ref([]);
// 部室人力资源状态
const employeeResourcesData = ref([]);
// 技术及业务培训情况
const trainingData = ref([]);
// 项目重点关注内容
const projectFocusData = ref([]);
// 部室人力符合情况
const lastMonthLoadChartRef = ref();
let lastMonthLoadChart = {};
const lastMonthLoadData = ref({ veryFull: 16, full: 81, generally: 0, noFull: 3 });
const theMonthLoadChartRef = ref();
let theMonthLoadChart = {};
const theMonthLoadData = ref({ veryFull: 13, full: 85, generally: 0, noFull: 2 });
let monthLoadOption = {
  title: { left: "center", top: "5%" },
  legend: { orient: "vertical", top: "middle", left: "right", itemHeight: 20, textStyle: { fontSize: 13 } },
  tooltip: { trigger: "item", formatter: "{b}：{c}%" },
  series: {
    type: "pie",
    center: ["50%", "55%"], //圆心位置
    radius: "60%", //饼图半径
    label: {
      position: "outside",
      formatter: "{b}：{c}%",
      fontSize: 13,
    },
  },
  emphasis: {
    itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: "rgb(0,0,0,0.5)" },
  },
};

let username = JSON.parse(sessionStorage.getItem("userInfo")).user.name;
// 采购部门员工集合
const purchasingEmpData = ref([]);

// 测试wcw2564、cb2353、cy2318、th2278、2023-01
// username = "cb2353";
// reportMonth.value = "2023-01";
onMounted(() => {
  ReportService.queryPurchasingEmp().then((res) => {
    purchasingEmpData.value = res.data;
  });
  queryReport();
  // lastMonthLoadChart = echarts.init(lastMonthLoadChartRef.value);
  // theMonthLoadChart = echarts.init(theMonthLoadChartRef.value);
  // buildLastMonthLoad();
  // buildTheMonthLoad();
});

const isLoading = ref(false);
const lastMonthReportProject = ref([]);
// 查询报告
const queryReport = () => {
  isLoading.value = true;
  // 查询上期报告项目情况
  ReportService.queryLastMonthReportProject({ reportMonth: dayjs(reportMonth.value).format("YYYY-MM") }).then((res) => {
    lastMonthReportProject.value = res.data;
  });
  ReportService.queryReport({ reportMonth: dayjs(reportMonth.value).format("YYYY-MM"), username: username, pageStatus: "report" }).then(
    (res) => {
      if (res.code === 200 && res.data) {
        projectDetailsData.value = res.data.projectDetails;
        isLoading.value = false;
        projectSituationData.value = res.data.projectSituation?.filter(
          (item) => item.projectSituation || item.projectProblem || item.projectSolution,
        );
        projectInquiryQuotationData.value = res.data.projectInquiryQuotation?.filter(
          (item) => item.projectInquiry !== null || item.projectQuotation !== null,
        );
        projectContractData.value = res.data.projectContract?.filter(
          (item) => item.projectContractCount !== null || item.projectContractAmount !== null,
        );
        projectDesignDocData.value = res.data.projectDesigndoc?.filter(
          (item) => item.docReturnCount !== null || item.docReceiveCount !== null || item.docSubmitCount !== null,
        );
        projectDeliveryInspectionData.value = res.data.projectDeliveryInspection?.filter(
          (item) =>
            item.projectOnlineDeliveryCount !== null ||
            item.projectOfflineDeliveryCount !== null ||
            item.projectSupervisionCount !== null ||
            item.projectInspectionCount !== null,
        );
        projectReceiveInspectionData.value = res.data.projectReceiveInspection?.filter(
          (item) =>
            item.projectReceiveGoodsCount !== null ||
            item.projectOpenboxCount !== null ||
            item.projectSupervisionInspectionCount !== null ||
            item.projectInstorageCount !== null ||
            item.projectOutstorageCount !== null ||
            item.projectBackupHandoverCount !== null ||
            item.projectDocArrangementCount !== null ||
            item.projectFactoryServiceCount !== null,
        );
        projectPaymentInvoiceData.value = res.data.projectPaymentInvoice?.filter(
          (item) =>
            item.projectPaymentCount !== null ||
            item.projectApplyPassCount !== null ||
            item.projectActualPayCount !== null ||
            item.projectInvoiceCount !== null ||
            item.projectTransferFinanceCount !== null,
        );
        projectControlPointData.value = res.data.projectControlPoint?.filter(
          (item) =>
            item.projectLastMonthLegacyCount !== null ||
            item.projectTheMonthPlanCount !== null ||
            item.projectAllPlanCount !== null ||
            item.projectCompleteRate !== null ||
            item.projectOwnerReasonCount !== null ||
            item.projectUpstreamReasonCount !== null ||
            item.projectProfessionalReasonCount !== null,
        );
        projectUncompleteReasonData.value = res.data.projectUncompleteReason?.filter(
          (item) => item.projectMainControlContent || item.projectUncompleteReason || item.projectSolution,
        );
        employeeResourcesData.value = res.data.employeeResources;
        trainingData.value = res.data.training;
        projectFocusData.value = res.data.projectFocus?.filter((item) => item.projectFocusContent);
      }
    },
  );
};

// 构造上月人力负荷饼图
const buildLastMonthLoad = () => {
  lastMonthLoadChart && lastMonthLoadChart.clear();
  monthLoadOption.title.text = "上月－采购部人力负荷情况图";
  monthLoadOption.series.data = [
    { value: lastMonthLoadData.value.veryFull, name: "非常饱满", itemStyle: { color: "#5470c6" } },
    { value: lastMonthLoadData.value.full, name: "饱满", itemStyle: { color: "#ee6666" } },
    { value: lastMonthLoadData.value.generally, name: "一般", itemStyle: { color: "#91cc75" } },
    { value: lastMonthLoadData.value.noFull, name: "不饱满", itemStyle: { color: "#fac858" } },
  ];
  lastMonthLoadChart.setOption(monthLoadOption);
};

// 构造本月人力负荷饼图
const buildTheMonthLoad = () => {
  theMonthLoadChart && theMonthLoadChart.clear();
  monthLoadOption.title.text = "本月－采购部人力负荷情况图";
  monthLoadOption.series.data = [
    { value: theMonthLoadData.value.veryFull, name: "非常饱满", itemStyle: { color: "#5470c6" } },
    { value: theMonthLoadData.value.full, name: "饱满", itemStyle: { color: "#ee6666" } },
    { value: theMonthLoadData.value.generally, name: "一般", itemStyle: { color: "#91cc75" } },
    { value: theMonthLoadData.value.noFull, name: "不饱满", itemStyle: { color: "#fac858" } },
  ];
  theMonthLoadChart.setOption(monthLoadOption);
};

const reportMonthChange = () => {
  queryReport();
};

const employeeNumInput = (val, type, row) => {
  row.allNum = val;
  if (type != "employee" && row.regularNum) {
    row.allNum += row.regularNum;
  }
  if (type != "rehire" && row.rehireNum) {
    row.allNum += row.rehireNum;
  }
  if (type != "external" && row.externalNum) {
    row.allNum += row.externalNum;
  }
  if (type != "borrow" && row.borrowNum) {
    row.allNum += row.borrowNum;
  }
};

const exportHandle = () => {
  // 根据项目导出设置过滤项目id
  const projectIds = projectDetailsData.value.filter((item) => item.projectExport).map((item) => item.projectId);
  if (projectIds.length === 0) {
    ElMessage.error("请勾选导出项目");
    return;
  }

  // 根据选中采购经理id读取采购经理名字
  for (let project of projectDetailsData.value) {
    let purchasingManagerArray = [];
    for (let empId of project.purchasingManagerList) {
      let purchasingEmp = purchasingEmpData.value.find((item) => item.id === empId);
      let empCname = purchasingEmp ? purchasingEmp.empCname : "";
      if (empCname) {
        purchasingManagerArray.push(empCname);
      }
    }
    project.purchasingManager = purchasingManagerArray ? purchasingManagerArray.toString() : "";
  }
  ReportService.saveReport({
    pageStatus: "report", // 报告状态
    reportMonth: dayjs(reportMonth.value).format("YYYY-MM"),
    reportLog: null,
    projectDetailsList: projectDetailsData.value,
    projectSituationList: null,
    projectInquiryQuotationList: null,
    projectContractList: null,
    projectDesigndocList: null,
    projectDeliveryInspectionList: null,
    projectReceiveInspectionList: null,
    projectPaymentInvoiceList: null,
    projectControlPointList: null,
    projectUncompleteReasonList: null,
    employeeResourcesList: null, // 目前只拉取数据，对数据不做保存
    trainingList: null,
    projectFocusList: null,
  }).then((res) => {
    if (res.code === 200) {
      queryReport();
    } else {
      ElMessage.error(res.msg);
    }
  });

  const url = "/template/MonthReportTemp.docx";
  JSZipUtils.getBinaryContent(url, (err, data) => {
    if (err) {
      ElMessage.error("导出报告出错");
      console.log("err:", err);
      return;
    }
    let zip = new JSZip(data);

    const Docxtemplater = require("docxtemplater");
    const ImageModule = require("docxtemplater-image-module-free");
    const imageOptions = {
      centered: false,
      getImage(tagValue, tagName) {
        return new Promise(function (resolve, reject) {
          JSZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error);
            }
            return resolve(content);
          });
        });
      },
      getSize(img, tagValue, tagName) {
        // 非固定大小（这里是设置宽度最大为500px的图片）
        return new Promise(function (resolve, reject) {
          let image = new Image();
          image.src = tagValue;
          let imgWidth, imgHeight, scale;
          image.onload = function () {
            imgWidth = image.width;
            imgHeight = image.height;
            scale = 0;
            if (imgWidth > 500) {
              scale = 500 / imgWidth;
              imgWidth = 500;
              imgHeight = imgHeight * scale;
            }
            resolve([imgWidth, imgHeight]);
          };
          image.onerror = function (e) {
            console.log("img, tagValue, tagName : ", img, tagValue, tagName);
            reject(e);
          };
        });
      },
    };
    const expressionParser = require("docxtemplater/expressions.js");
    const nullGetter = (part, scopeManager) => {
      if (!part.module) {
        return "";
      }
    };
    let doc = new Docxtemplater(zip, { parser: expressionParser, nullGetter: nullGetter, modules: [new ImageModule(imageOptions)] });

    let reportInfo = {};
    // 报告期
    reportInfo.reportMonth = dayjs(reportMonth.value).format("YYYY年M月");
    // 报告编号
    reportInfo.reportNo = "CG-MR-" + dayjs(reportMonth.value).format("YYYY-M");
    // 发布日期
    reportInfo.publishDate = dayjs(new Date()).format("YYYY年MM月DD日");

    // 项目详细情况
    projectDetailsData.value = projectDetailsData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    projectDetailsData.value.forEach((item, index) => (item.sortNo = index + 1));
    reportInfo.projectDetailsList = projectDetailsData.value;

    // 项目运行数量
    // 本期项目运行数量
    reportInfo.month = dayjs(reportMonth.value).format("M");
    const allProjects = projectDetailsData.value;
    reportInfo.allCounts = allProjects.length;
    const epcProjects = projectDetailsData.value.filter((item) => item.projectStage === "总承包");
    reportInfo.epcCounts = epcProjects.length;
    const epcmProjects = projectDetailsData.value.filter((item) => item.projectStage === "管理包");
    reportInfo.epcmCounts = epcmProjects.length;
    const bidProjects = projectDetailsData.value.filter((item) => item.projectStage === "投标报价");
    reportInfo.bidCounts = bidProjects.length;
    // 上期项目运行数量
    const lastMonthEpcProjects = lastMonthReportProject.value.filter((item) => item.projectStage === "总承包");
    const lastMonthEpcmProjects = lastMonthReportProject.value.filter((item) => item.projectStage === "管理包");
    const lastMonthBidProjects = lastMonthReportProject.value.filter((item) => item.projectStage === "投标报价");
    // 对比本期项目运行数量和上期增加的差异
    const diffEpcCounts = epcProjects.length - lastMonthEpcProjects.length;
    const diffEpcmCounts = epcmProjects.length - lastMonthEpcmProjects.length;
    const diffBidCounts = bidProjects.length - lastMonthBidProjects.length;
    // 对比本期项目和上期增加的差异
    const diffEpcProjects = getDiffProjects(epcProjects, lastMonthEpcProjects);
    const diffEpcmProjects = getDiffProjects(epcmProjects, lastMonthEpcmProjects);
    const diffBidProjects = getDiffProjects(bidProjects, lastMonthBidProjects);
    // 总结项目执行情况
    reportInfo.epcSummary =
      "本期增加总承包项目：" + (diffEpcCounts > 0 ? diffEpcProjects.map((item) => item.projectName).join("、") : "无");
    reportInfo.epcmSummary =
      "本期增加管理包项目：" + (diffEpcmCounts > 0 ? diffEpcmProjects.map((item) => item.projectName).join("、") : "无");
    reportInfo.bitSummary =
      "本期增加投标报价项目：" + (diffBidCounts > 0 ? diffBidProjects.map((item) => item.projectName).join("、") : "无");

    // 项目执行情况
    projectSituationData.value = projectSituationData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    projectSituationData.value.forEach((item, index) => (item.sortNo = index + 1));
    reportInfo.projectSituationList = projectSituationData.value;

    // 项目询价报价情况
    let allProjectInquiry = 0;
    let allProjectQuotation = 0;
    projectInquiryQuotationData.value = projectInquiryQuotationData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    for (let i in projectInquiryQuotationData.value) {
      projectInquiryQuotationData.value[i].sortNo = Number(i) + 1;
      projectInquiryQuotationData.value[i].isAll = false;
      allProjectInquiry += projectInquiryQuotationData.value[i].projectInquiry;
      allProjectQuotation += projectInquiryQuotationData.value[i].projectQuotation;
    }
    if (projectInquiryQuotationData.value && projectInquiryQuotationData.value.length > 0) {
      projectInquiryQuotationData.value.push({
        isAll: true,
        projectName: "合计",
        projectInquiry: allProjectInquiry,
        projectQuotation: allProjectQuotation,
      });
    }
    reportInfo.projectInquiryQuotationList = projectInquiryQuotationData.value;

    // 合同签订情况
    let allProjectContractCount = new Decimal(0);
    let allProjectContractAmount = new Decimal(0);
    projectContractData.value = projectContractData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    for (let i in projectContractData.value) {
      const projectContract = projectContractData.value[i];
      projectContract.sortNo = Number(i) + 1;
      projectContract.isAll = false;
      allProjectContractCount = Decimal.add(allProjectContractCount, projectContract.projectContractCount);
      allProjectContractAmount = Decimal.add(allProjectContractAmount, projectContract.projectContractAmount);
    }
    if (projectContractData.value && projectContractData.value.length > 0) {
      projectContractData.value.push({
        isAll: true,
        projectName: "合计",
        projectContractCount: allProjectContractCount.toString(),
        projectContractAmount: allProjectContractAmount.toString(),
      });
    }
    reportInfo.projectContractList = projectContractData.value;

    // 厂商返回设计文件的接收和提交情况
    let AllDocReturnCount = 0;
    let AllDocReceiveCount = 0;
    let AllDocSubmitCount = 0;
    projectDesignDocData.value = projectDesignDocData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    for (let i in projectDesignDocData.value) {
      projectDesignDocData.value[i].sortNo = Number(i) + 1;
      projectDesignDocData.value[i].isAll = false;
      AllDocReturnCount += projectDesignDocData.value[i].docReturnCount;
      AllDocReceiveCount += projectDesignDocData.value[i].docReceiveCount;
      AllDocSubmitCount += projectDesignDocData.value[i].docSubmitCount;
    }
    if (projectDesignDocData.value && projectDesignDocData.value.length > 0) {
      projectDesignDocData.value.push({
        isAll: true,
        projectName: "合计",
        docReturnCount: AllDocReturnCount,
        docReceiveCount: AllDocReceiveCount,
        docSubmitCount: AllDocSubmitCount,
      });
    }
    reportInfo.projectDesignDocList = projectDesignDocData.value;

    // 催交和中间检验情况
    let AllProjectOnlineDeliveryCount = 0;
    let AllProjectOfflineDeliveryCount = 0;
    let AllProjectSupervisionCount = 0;
    let AllProjectInspectionCount = 0;
    projectDeliveryInspectionData.value = projectDeliveryInspectionData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    for (let i in projectDeliveryInspectionData.value) {
      projectDeliveryInspectionData.value[i].sortNo = Number(i) + 1;
      projectDeliveryInspectionData.value[i].isAll = false;
      AllProjectOnlineDeliveryCount += projectDeliveryInspectionData.value[i].projectOnlineDeliveryCount;
      AllProjectOfflineDeliveryCount += projectDeliveryInspectionData.value[i].projectOfflineDeliveryCount;
      AllProjectSupervisionCount += projectDeliveryInspectionData.value[i].projectSupervisionCount;
      AllProjectInspectionCount += projectDeliveryInspectionData.value[i].projectInspectionCount;
    }
    if (projectDeliveryInspectionData.value && projectDeliveryInspectionData.value.length > 0) {
      projectDeliveryInspectionData.value.push({
        isAll: true,
        projectName: "合计",
        projectOnlineDeliveryCount: AllProjectOnlineDeliveryCount,
        projectOfflineDeliveryCount: AllProjectOfflineDeliveryCount,
        projectSupervisionCount: AllProjectSupervisionCount,
        projectInspectionCount: AllProjectInspectionCount,
      });
    }
    reportInfo.projectDeliveryInspectionList = projectDeliveryInspectionData.value;

    // 现场接保检工作情况
    let AllProjectReceiveGoodsCount = 0;
    let AllProjectOpenboxCount = 0;
    let AllProjectSupervisionInspectionCount = 0;
    let AllProjectInstorageCount = 0;
    let AllProjectOutstorageCount = 0;
    let AllProjectBackupHandoverCount = 0;
    let AllProjectDocArrangementCount = 0;
    let AllProjectFactoryServiceCount = 0;
    projectReceiveInspectionData.value = projectReceiveInspectionData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    for (let i in projectReceiveInspectionData.value) {
      projectReceiveInspectionData.value[i].sortNo = Number(i) + 1;
      projectReceiveInspectionData.value[i].isAll = false;
      AllProjectReceiveGoodsCount += projectReceiveInspectionData.value[i].projectReceiveGoodsCount;
      AllProjectOpenboxCount += projectReceiveInspectionData.value[i].projectOpenboxCount;
      AllProjectSupervisionInspectionCount += projectReceiveInspectionData.value[i].projectSupervisionInspectionCount;
      AllProjectInstorageCount += projectReceiveInspectionData.value[i].projectInstorageCount;
      AllProjectOutstorageCount += projectReceiveInspectionData.value[i].projectOutstorageCount;
      AllProjectBackupHandoverCount += projectReceiveInspectionData.value[i].projectBackupHandoverCount;
      AllProjectDocArrangementCount += projectReceiveInspectionData.value[i].projectDocArrangementCount;
      AllProjectFactoryServiceCount += projectReceiveInspectionData.value[i].projectFactoryServiceCount;
    }
    if (projectReceiveInspectionData.value && projectReceiveInspectionData.value.length > 0) {
      projectReceiveInspectionData.value.push({
        isAll: true,
        projectName: "合计",
        projectReceiveGoodsCount: AllProjectReceiveGoodsCount,
        projectOpenboxCount: AllProjectOpenboxCount,
        projectSupervisionInspectionCount: AllProjectSupervisionInspectionCount,
        projectInstorageCount: AllProjectInstorageCount,
        projectOutstorageCount: AllProjectOutstorageCount,
        projectBackupHandoverCount: AllProjectBackupHandoverCount,
        projectDocArrangementCount: AllProjectDocArrangementCount,
        projectFactoryServiceCount: AllProjectFactoryServiceCount,
      });
    }
    reportInfo.projectReceiveInspectionList = projectReceiveInspectionData.value;

    // 货款支付和发票收取情况
    let AllProjectPaymentCount = 0;
    let AllProjectApplyPassCount = 0;
    let AllProjectActualPayCount = 0;
    let AllProjectInvoiceCount = 0;
    let AllProjectTransferFinanceCount = 0;
    projectPaymentInvoiceData.value = projectPaymentInvoiceData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    for (let i in projectPaymentInvoiceData.value) {
      projectPaymentInvoiceData.value[i].sortNo = Number(i) + 1;
      projectPaymentInvoiceData.value[i].isAll = false;
      AllProjectPaymentCount += projectPaymentInvoiceData.value[i].projectPaymentCount;
      AllProjectApplyPassCount += projectPaymentInvoiceData.value[i].projectApplyPassCount;
      AllProjectActualPayCount += projectPaymentInvoiceData.value[i].projectActualPayCount;
      AllProjectInvoiceCount += projectPaymentInvoiceData.value[i].projectInvoiceCount;
      AllProjectTransferFinanceCount += projectPaymentInvoiceData.value[i].projectTransferFinanceCount;
    }
    if (projectPaymentInvoiceData.value && projectPaymentInvoiceData.value.length > 0) {
      projectPaymentInvoiceData.value.push({
        isAll: true,
        projectName: "合计",
        projectPaymentCount: AllProjectPaymentCount,
        projectApplyPassCount: AllProjectApplyPassCount,
        projectActualPayCount: AllProjectActualPayCount,
        projectInvoiceCount: AllProjectInvoiceCount,
        projectTransferFinanceCount: AllProjectTransferFinanceCount,
      });
    }
    reportInfo.projectPaymentInvoiceList = projectPaymentInvoiceData.value;

    // 控制点完成情况
    projectControlPointData.value = projectControlPointData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    for (let i in projectControlPointData.value) {
      const projectControlPoint = projectControlPointData.value[i];
      projectControlPoint.sortNo = Number(i) + 1;
      projectControlPoint.projectCompletePercent =
        projectControlPoint.projectCompleteRate !== null ? Number(projectControlPoint.projectCompleteRate * 100).toFixed(0) : "";
    }
    projectControlPointData.value = projectControlPointData.value.filter(
      (item) =>
        item.projectLastMonthLegacyCount +
          item.projectTheMonthPlanCount +
          item.projectAllPlanCount +
          item.projectCompleteCount +
          item.projectUncompleteCount +
          item.projectOwnerReasonCount +
          item.projectUpstreamReasonCount +
          item.projectProfessionalReasonCount >
        0,
    );
    reportInfo.projectControlPointList = projectControlPointData.value;

    // 未完控制点原因说明
    projectUncompleteReasonData.value = projectUncompleteReasonData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    projectUncompleteReasonData.value.forEach((item, index) => (item.sortNo = index + 1));
    projectUncompleteReasonData.value = projectUncompleteReasonData.value.filter(
      (item) => item.projectMainControlContent && item.projectUncompleteReason && item.projectSolution,
    );
    reportInfo.projectUncompleteReasonList = projectUncompleteReasonData.value;

    // 部室人力资源状态
    let allRegularNum = 0;
    let allRehireNum = 0;
    let allExternalNum = 0;
    let allBorrowNum = 0;
    let allNum = 0;
    for (let i in employeeResourcesData.value) {
      allRegularNum += employeeResourcesData.value[i].regularNum;
      allRehireNum += employeeResourcesData.value[i].rehireNum;
      employeeResourcesData.value[i].externalNum += employeeResourcesData.value[i].borrowNum;
      allExternalNum += employeeResourcesData.value[i].externalNum;
      allBorrowNum += employeeResourcesData.value[i].borrowNum;
      allNum += employeeResourcesData.value[i].allNum;
    }
    if (employeeResourcesData.value && employeeResourcesData.value.length > 0) {
      employeeResourcesData.value.push({
        employeeType: "合计",
        regularNum: allRegularNum,
        rehireNum: allRehireNum,
        externalNum: allExternalNum,
        borrowNum: allBorrowNum,
        allNum: allNum,
      });
    }
    reportInfo.employeeResourcesList = employeeResourcesData.value;

    // 部室人力负荷情况
    // const lastMonthLoadChartImage = new Image();
    // lastMonthLoadChartImage.src = lastMonthLoadChart.getDataURL({
    //   pixelRatio: 2, // 导出的图片分辨率比例，默认为 1。
    //   backgroundColor: "#fff", // 导出的图片背景色，默认使用 option 里的 backgroundColor
    // });
    // reportInfo.lastMonthLoadChartImage = lastMonthLoadChartImage.src;

    // const theMonthLoadChartImage = new Image();
    // theMonthLoadChartImage.src = theMonthLoadChart.getDataURL({
    //   pixelRatio: 2, // 导出的图片分辨率比例，默认为 1。
    //   backgroundColor: "#fff", // 导出的图片背景色，默认使用 option 里的 backgroundColor
    // });
    // reportInfo.theMonthLoadChartImage = theMonthLoadChartImage.src;

    // 技术及业务培训情况
    trainingData.value.forEach((item, index) => (item.sortNo = index + 1));
    reportInfo.trainingList = trainingData.value;

    // 项目运行过程中的主要工作
    projectFocusData.value = projectFocusData.value.filter((item) => projectIds.indexOf(item.projectId) > -1);
    projectFocusData.value.forEach((item, index) => (item.sortNo = index + 1));
    reportInfo.projectFocusList = projectFocusData.value;

    doc.resolveData({ ...reportInfo }).then(() => {
      doc.render();
      let out = doc.getZip().generate({
        type: "blob",
        MimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      saveAs(out, "采购部月生产报告-" + reportInfo.reportMonth + ".docx");
    });
  });
};

// 比较大项目数组比小项目数组多哪些项目
const getDiffProjects = (appleProjects, bananaProjects) => {
  let diffProjects = appleProjects.filter((item) => bananaProjects.filter((jtem) => item.projectId === jtem.projectId).length < 1);
  return diffProjects;
};
</script>
<style scoped>
.mb-15 {
  margin-bottom: 15px;
}
.mt-15 {
  margin-top: 15px;
}
.ml-15 {
  margin-left: 15px;
}
.h1-font {
  font-size: 26px;
  font-weight: bold;
}
.h2-font {
  font-size: 20px;
  font-weight: bold;
}
.h3-font {
  font-size: 16px;
  font-weight: bold;
}
.h3-font-nobold {
  font-size: 16px;
}
.el-table :deep() .header-cell {
  background: #f5f7fa !important;
}
</style>
